package sg.edu.nus.iss.cats.action;

import javax.servlet.http.*;
import org.apache.struts.action.*;

import sg.edu.nus.iss.cats.model.*;
import sg.edu.nus.iss.cats.controller.*;
import sg.edu.nus.iss.cats.dataaccess.*;

import java.util.Vector;

public class EmployeeHistoryAction extends Action {

 
	public ActionForward execute(ActionMapping mapping,
                                 ActionForm form,
                                 HttpServletRequest request,
                                 HttpServletResponse response) {
                                    
        ActionErrors errors = new ActionErrors();

        try {

            System.out.println("In EmployeeHistoryAction");

            HttpSession session = request.getSession();
            UserSession userSession =
                (UserSession) session.getAttribute("USERSESSION");

            Employee employee = null;
            String employeeId = request.getParameter("employee_id");
            if (employeeId != null) {
                EmployeeDAO empDAO = DAOFactory.getInstance().getEmployeeDAO();
                employee = empDAO.findEmployee(employeeId);
            } else {
                employee = userSession.getEmployee();
                employeeId = employee.getEmployeeId();
            }

            System.out.println(
                "EmployeeHistoryAction " + employee.getEmployeeId());
                
            CourseDAO courseDAO = DAOFactory.getInstance().getCourseDAO();
            Course[] courses = courseDAO.findCoursesByEmployee(employeeId);
            
            System.out.println("Got courses" + courses.length);


            Vector v = new Vector();
            for (int i=0;i<courses.length;i++){

                v.add(courses[i]);
            }
            EmployeeCourses courseList = new EmployeeCourses();
            courseList.setEmployee(employee);
            courseList.setCourses(v);

            EmployeeCourses[] result = new EmployeeCourses[] { courseList };
            request.setAttribute("employeeCourseLists", result);

            System.out.println("Completed EmployeeHistoryAction");

            return mapping.findForward("success");

        } catch (Exception e) {
            //return an ActionForward respresenting the logical failure page
            errors.add(
                ActionErrors.GLOBAL_ERROR,
                new ActionError("error.employee.notfound"));
            // Report any errors we have discovered back to the original form
            saveErrors(request, errors);
            System.out.println("EmployeeHistoryAction: " + e.toString());
            servlet.log(
                "EmployeeHistoryAction: Employee could not be found in session ",
                0);
            return mapping.findForward("error");
        }
    }
}